import { ref, computed, reactive } from 'vue'
import { roomAPI, buildingAPI, labelAPI, bedAPI } from '../apis/roomAPI'
import { mockBuildings, mockLabels, mockRooms, mockBeds, createMockResponse, mockDelay } from '../data/mockData'

// 房间管理组合式函数
export function useRoom() {
  // 响应式数据
  const rooms = ref([])
  const buildings = ref([])
  const labels = ref([])
  const beds = ref([])
  const loading = ref(false)
  const error = ref(null)

  // 搜索和筛选状态
  const filters = reactive({
    searchQuery: '',
    status: '',
    buildingId: '',
    floor: '',
    type: '',
    labelIds: []
  })

  // 分页状态
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 计算属性
  const filteredRooms = computed(() => {
    let filtered = rooms.value

    // 搜索过滤
    if (filters.searchQuery) {
      const query = filters.searchQuery.toLowerCase()
      filtered = filtered.filter(room => 
        room.number.toLowerCase().includes(query) ||
        room.description?.toLowerCase().includes(query) ||
        getBuildingName(room.buildingId).toLowerCase().includes(query)
      )
    }

    // 状态过滤
    if (filters.status) {
      filtered = filtered.filter(room => room.status === filters.status)
    }

    // 楼栋过滤
    if (filters.buildingId) {
      filtered = filtered.filter(room => room.buildingId === filters.buildingId)
    }

    // 楼层过滤
    if (filters.floor) {
      filtered = filtered.filter(room => room.floor === filters.floor)
    }

    // 类型过滤
    if (filters.type) {
      filtered = filtered.filter(room => room.type === filters.type)
    }

    // 标签过滤
    if (filters.labelIds.length > 0) {
      filtered = filtered.filter(room => 
        filters.labelIds.some(labelId => room.labelIds?.includes(labelId))
      )
    }

    return filtered
  })

  const paginatedRooms = computed(() => {
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    return filteredRooms.value.slice(start, end)
  })

  const totalPages = computed(() => 
    Math.ceil(filteredRooms.value.length / pagination.pageSize)
  )

  // 统计信息
  const stats = computed(() => ({
    total: rooms.value.length,
    available: rooms.value.filter(room => room.status === 'available').length,
    occupied: rooms.value.filter(room => room.status === 'occupied').length,
    maintenance: rooms.value.filter(room => room.status === 'maintenance').length,
    inactive: rooms.value.filter(room => room.status === 'inactive').length
  }))

  // 楼层列表
  const floors = computed(() => {
    const floorSet = new Set(rooms.value.map(room => room.floor))
    return Array.from(floorSet).sort((a, b) => a - b)
  })

  // 可用标签
  const availableLabels = computed(() => 
    labels.value.filter(label => label.status !== 'inactive')
  )

  // 方法
  const getBuildingName = (buildingId) => {
    const building = buildings.value.find(b => b.id === buildingId)
    return building ? building.name : '未知楼栋'
  }

  const getRoomLabels = (labelIds) => {
    return labels.value.filter(label => labelIds?.includes(label.id))
  }

  const getRoomBeds = (roomId) => {
    return beds.value.filter(bed => bed.roomId === roomId)
  }

  const getOccupancyRate = (room) => {
    if (!room.totalBeds) return 0
    return Math.round((room.occupiedBeds / room.totalBeds) * 100)
  }

  // API 调用方法（使用模拟数据）
  const fetchRooms = async () => {
    try {
      loading.value = true
      error.value = null
      await mockDelay(300)
      rooms.value = [...mockRooms]
    } catch (err) {
      error.value = err.message
      console.error('获取房间列表失败:', err)
    } finally {
      loading.value = false
    }
  }

  const fetchBuildings = async () => {
    try {
      await mockDelay(200)
      buildings.value = [...mockBuildings]
    } catch (err) {
      console.error('获取楼栋列表失败:', err)
    }
  }

  const fetchLabels = async () => {
    try {
      await mockDelay(200)
      labels.value = [...mockLabels]
    } catch (err) {
      console.error('获取标签列表失败:', err)
    }
  }

  const fetchBeds = async () => {
    try {
      await mockDelay(200)
      beds.value = [...mockBeds]
    } catch (err) {
      console.error('获取床位列表失败:', err)
    }
  }

  const createRoom = async (roomData) => {
    try {
      loading.value = true
      await mockDelay(500)
      const newRoom = {
        id: Date.now(),
        ...roomData,
        occupiedBeds: 0,
        createdAt: new Date().toISOString().split('T')[0],
        updatedAt: new Date().toISOString().split('T')[0]
      }
      rooms.value.push(newRoom)
      return newRoom
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }

  const updateRoom = async (id, roomData) => {
    try {
      loading.value = true
      await mockDelay(500)
      const index = rooms.value.findIndex(room => room.id === id)
      if (index > -1) {
        rooms.value[index] = {
          ...rooms.value[index],
          ...roomData,
          updatedAt: new Date().toISOString().split('T')[0]
        }
        return rooms.value[index]
      }
      throw new Error('房间不存在')
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }

  const deleteRoom = async (id) => {
    try {
      loading.value = true
      await mockDelay(300)
      const index = rooms.value.findIndex(room => room.id === id)
      if (index > -1) {
        rooms.value.splice(index, 1)
      } else {
        throw new Error('房间不存在')
      }
    } catch (err) {
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }

  const updateRoomStatus = async (id, status) => {
    try {
      await mockDelay(200)
      const room = rooms.value.find(r => r.id === id)
      if (room) {
        room.status = status
        room.updatedAt = new Date().toISOString().split('T')[0]
      } else {
        throw new Error('房间不存在')
      }
    } catch (err) {
      error.value = err.message
      throw err
    }
  }

  const updateRoomLabels = async (id, labelIds) => {
    try {
      await mockDelay(200)
      const room = rooms.value.find(r => r.id === id)
      if (room) {
        room.labelIds = labelIds
        room.updatedAt = new Date().toISOString().split('T')[0]
      } else {
        throw new Error('房间不存在')
      }
    } catch (err) {
      error.value = err.message
      throw err
    }
  }

  const searchRooms = async (query) => {
    try {
      await mockDelay(300)
      const filtered = rooms.value.filter(room => 
        room.number.toLowerCase().includes(query.toLowerCase()) ||
        room.description?.toLowerCase().includes(query.toLowerCase()) ||
        getBuildingName(room.buildingId).toLowerCase().includes(query.toLowerCase())
      )
      return filtered
    } catch (err) {
      error.value = err.message
      throw err
    }
  }

  const exportRooms = async (format = 'excel') => {
    try {
      await mockDelay(1000)
      // 模拟导出功能
      console.log(`导出房间数据为 ${format} 格式`)
      return { message: '导出成功' }
    } catch (err) {
      error.value = err.message
      throw err
    }
  }

  // 重置筛选器
  const resetFilters = () => {
    filters.searchQuery = ''
    filters.status = ''
    filters.buildingId = ''
    filters.floor = ''
    filters.type = ''
    filters.labelIds = []
  }

  // 重置分页
  const resetPagination = () => {
    pagination.currentPage = 1
  }

  // 初始化数据
  const initialize = async () => {
    await Promise.all([
      fetchRooms(),
      fetchBuildings(),
      fetchLabels(),
      fetchBeds()
    ])
  }

  return {
    // 状态
    rooms,
    buildings,
    labels,
    beds,
    loading,
    error,
    filters,
    pagination,

    // 计算属性
    filteredRooms,
    paginatedRooms,
    totalPages,
    stats,
    floors,
    availableLabels,

    // 方法
    getBuildingName,
    getRoomLabels,
    getRoomBeds,
    getOccupancyRate,
    fetchRooms,
    fetchBuildings,
    fetchLabels,
    fetchBeds,
    createRoom,
    updateRoom,
    deleteRoom,
    updateRoomStatus,
    updateRoomLabels,
    searchRooms,
    exportRooms,
    resetFilters,
    resetPagination,
    initialize
  }
}

// 房间状态管理
export function useRoomStatus() {
  const statusOptions = [
    { value: 'available', label: '可用', color: 'green' },
    { value: 'occupied', label: '已住满', color: 'red' },
    { value: 'maintenance', label: '维修中', color: 'yellow' },
    { value: 'inactive', label: '停用', color: 'gray' }
  ]

  const getStatusText = (status) => {
    const option = statusOptions.find(opt => opt.value === status)
    return option ? option.label : status
  }

  const getStatusColor = (status) => {
    const option = statusOptions.find(opt => opt.value === status)
    return option ? option.color : 'gray'
  }

  return {
    statusOptions,
    getStatusText,
    getStatusColor
  }
}

// 房间类型管理
export function useRoomType() {
  const typeOptions = [
    { value: 'standard', label: '标准间' },
    { value: 'deluxe', label: '豪华间' },
    { value: 'suite', label: '套房' }
  ]

  const getTypeText = (type) => {
    const option = typeOptions.find(opt => opt.value === type)
    return option ? option.label : type
  }

  return {
    typeOptions,
    getTypeText
  }
}
